package com.ruoyi.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.web.service.FileService;
import com.ruoyi.web.service.IdentityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;

/**
 * @author zr 2024/2/29
 */
@Slf4j
@RestController
@Api(tags = "文件管理")
@RequestMapping("/wx")
public class FoodController {
    @Autowired
    private FileService fileService;
    @Autowired
    private IdentityService identityService;

    /**
     * 文件上传+识别接口
     *
     * @param file
     * @return
     */
    @PostMapping("/food/identify")
    @ApiOperation(value = "文件上传+识别")
    public AjaxResult identify(@RequestPart("file") MultipartFile file) throws Exception {
        String imgFileStr = fileService.upload(file, "src/food/" + file.getOriginalFilename());
        // 获取url
        String url = fileService.getUrl("src/food/" + file.getOriginalFilename()).toString();
        String identifyResult = identityService.identify(url);
        JSONObject jsonObject = JSONObject.parseObject(identifyResult);
        if (imgFileStr == null || "".equals(imgFileStr)) {
            return AjaxResult.error("文件上传失败");
        } else {
            System.err.println(jsonObject);
            // 删除图片,节省oss资源
            fileService.del(imgFileStr);
            return AjaxResult.success(jsonObject);
        }
    }
}
